package com.firmail.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.firmail.mock.util.GsonUtils;
import com.firmail.service.IMockDataDisposeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class JsonDataDisposeServImpl implements IMockDataDisposeService {

    @Override
    public String escapingData(String json) {
        log.info("the json before escaping: {}",json);
        Pattern p = Pattern.compile("\\\\\"");
        Matcher m = p.matcher(json);
        StringBuffer stringBuffer = new StringBuffer();
        String uuid= null;
        if (m.find()){
            uuid=getUUID();
            m.reset();
        }

        while (m.find()) {

            m.appendReplacement(stringBuffer, uuid);
        }
        m.appendTail(stringBuffer);
        String firstEsStr= stringBuffer.toString();
        String esData= uuid !=null ?firstEsStr.replaceAll("[\"\b]","\\\\\"").
                replaceAll(uuid,"\\\\\\\\\\\\\""):firstEsStr.replaceAll("[\"\b]","\\\\\"");

        //escape ,match two different situation [",|,]
        esData=esData.replaceAll("\\,\\\\\"","\\\\,\\\\\"").
                replaceAll("\\}\\,\\{","\\}\\\\,\\{");
        log.info("Escaping the json data: {}",esData);
        return esData;
    }


    public static String getUUID(){
        return UUID.randomUUID().toString();
    }
    public static void main(String[] args) {
        String json = "{name\":\"学习\",  \"age\":24,\"emailAddress\"   :  \n\"2457@123.com\",\n" +
                "  \"uuu\": [\n" +
                "    {\n" +
                "      \"jjj\": \"99\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"yyyy\": 88\n" +
                "    }\n" +
                "  ]}";

        JsonDataDisposeServImpl jsonDataProcessImpl= new JsonDataDisposeServImpl();
//        String data=jsonDataProcessImpl.processData(json);
//        System.out.println(data);
//        System.out.println("--------------------");

        jsonDataProcessImpl.escapingData(GsonUtils.toJson(GsonUtils.parseJson(json, Object.class)));
        System.out.println("----------------------------------");
        Pattern p = Pattern.compile("cat");
        Matcher m = p.matcher("one cat two cats three cats in the yard");
        StringBuffer sb = new StringBuffer();
        if (m.find()){
            System.out.println("dddddddddddddddddddddddddddddd");
            m=m.reset();
        }
        while (m.find()) {
            m.appendReplacement(sb, "dog");
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
        System.out.println("----------------------------------");
        JSONObject jsonStr= JSONObject.parseObject(json);
        System.out.println(JSONObject.toJSON(jsonStr));

    }

}
